package com.buddies.lottery.ui.register;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.blankj.utilcode.util.EncryptUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.buddies.lottery.App;
import com.buddies.lottery.R;
import com.buddies.lottery.base.BaseActivity;
import com.buddies.lottery.data.bean.User;
import com.buddies.lottery.ui.MainActivity;
import com.buddies.lottery.ui.login.LoginActivity;
import com.buddies.lottery.utils.AppExitUtils;
import com.r0adkll.slidr.Slidr;


public class RegisterActivity extends BaseActivity<RegisterContract.Presenter> implements View.OnClickListener, RegisterContract.View {

    private static final int REQUEST_MOBILE_LOGIN= 1;

    private Button mRegisterBTN;
    private EditText mPhoneET;
    private EditText mPwdET;
    private EditText mCodeET;
    private ImageView mClearPhoneIV;
    private ImageView mClearPwdIV;
    private ImageView mClearCodeIV;

    private String from;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getWindow().setBackgroundDrawableResource(R.color.transparent);
        Slidr.attach(this, App.getSlidrConfig());
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_register;
    }

    @Override
    protected void initView() {
        setUp();

        mRegisterBTN = (Button)findViewById(R.id.btn_register);
        mPhoneET = (EditText)findViewById(R.id.et_phone);
        mPwdET = (EditText)findViewById(R.id.et_pwd);
        mCodeET = (EditText)findViewById(R.id.et_code);
        mClearPhoneIV = (ImageView)findViewById(R.id.iv_clear);
        mClearPwdIV = (ImageView)findViewById(R.id.iv_clear_pwd);
        mClearCodeIV = (ImageView)findViewById(R.id.iv_clear_code);

        mRegisterBTN.setOnClickListener(this);
        mClearPhoneIV.setOnClickListener(this);
        mClearPwdIV.setOnClickListener(this);
        mClearCodeIV.setOnClickListener(this);
        findViewById(R.id.tv_pwd_login).setOnClickListener(this);
    }

    protected boolean isFromForgetPwd() {
        return "forgetPwd".equals(from);
    }

    @Override
    protected void initData() {
        mPresenter = new RegisterPresenter(this);

        Intent intent = getIntent();
        if (intent != null) {
            from = intent.getStringExtra("from");
            mPhoneET.setText(intent.getStringExtra("phone"));
        }

        if (isFromForgetPwd()){
            setTitle(getResources().getString(R.string.register_forget_pwd));
            mRegisterBTN.setText(R.string.register_commit);
            mPwdET.setHint(getResources().getString(R.string.login_pwd_hint_new));
            findViewById(R.id.tv_tips).setVisibility(View.VISIBLE);
            findViewById(R.id.tv_pwd_login).setVisibility(View.GONE);
        } else {
            setTitle(getResources().getString(R.string.register));
            mRegisterBTN.setText(R.string.register);
            mPwdET.setHint(getResources().getString(R.string.login_pwd_hint));
            findViewById(R.id.tv_tips).setVisibility(View.GONE);
            findViewById(R.id.tv_pwd_login).setVisibility(View.VISIBLE);
        }
        findViewById(R.id.ll_password).setVisibility(View.VISIBLE);
        findViewById(R.id.line_password).setVisibility(View.VISIBLE);

        mPhoneET.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                mClearPhoneIV.setVisibility(editable.length() == 0 ? View.GONE : View.VISIBLE);
                setCommitBtnEnable();
            }
        });
        mPhoneET.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean hasFocus) {
                mClearPhoneIV.setVisibility(mPhoneET.length() == 0 || !hasFocus ? View.GONE : View.VISIBLE);
            }
        });

        mPwdET.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                mClearPwdIV.setVisibility(editable.length() == 0 ? View.GONE : View.VISIBLE);
                setCommitBtnEnable();
            }
        });
        mPwdET.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean hasFocus) {
                mClearPwdIV.setVisibility(mPwdET.length() == 0 || !hasFocus ? View.GONE : View.VISIBLE);
            }
        });

        mCodeET.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                mClearCodeIV.setVisibility(editable.length() == 0 ? View.GONE : View.VISIBLE);
                setCommitBtnEnable();
            }
        });
        mCodeET.setOnFocusChangeListener(new View.OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                mClearCodeIV.setVisibility(mCodeET.length() == 0 || !hasFocus ? View.GONE : View.VISIBLE);
            }
        });

        setCommitBtnEnable();
    }

    public void setCommitBtnEnable() {
        boolean enabled = mPhoneET.length() > 0 && mCodeET.length() > 0 && (!isFromForgetPwd() || mPwdET.length() > 0);
        mRegisterBTN.setEnabled(enabled);
        if (!enabled) {
            mRegisterBTN.setAlpha(0.5f);
        } else {
            mRegisterBTN.setAlpha(1.0f);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_register:
                if (checkPhone() && checkCode() && (!isFromForgetPwd() || checkPwd())) {
                    requestRegister();
                }
                KeyboardUtils.hideSoftInput(getActivity());
                break;

            case R.id.iv_clear:
                mPhoneET.setText("");
                break;

            case R.id.iv_clear_pwd:
                mPwdET.setText("");
                break;

            case R.id.iv_clear_code:
                mCodeET.setText("");
                break;

            case R.id.tv_pwd_login:
                Intent intent = new Intent();
                intent.setClass(this, LoginActivity.class);
                intent.putExtra("phone", getPhone());
                startActivityForResult(intent, REQUEST_MOBILE_LOGIN);
                finish();
                break;

            default:
                break;
        }
    }

    private void requestRegister() {
        final String phone = getPhone();
        final String pwd = getPwd();
        mPresenter.postRegister(phone, EncryptUtils.encryptMD5ToString(pwd));
        showProgressDialog(R.string.register_processing);
    }

    @Override
    public void registerSuccess(User user) {
        showToast(R.string.register_success);

        if (isTaskRoot()) {
            MainActivity.launch(getActivity());
        }

        setResult(RESULT_OK);
        finish();
    }

    private boolean checkPhone() {
        String phone = getPhone();

        boolean check = false;
        if (TextUtils.isEmpty(phone)) {
            showToast(getString(R.string.login_phone_number_require));
        } else if (phone.contains(" ")) {
            showToast(getString(R.string.login_phone_number_not_blank));
        } else if (phone.length() < 6 || phone.length() > 18) {
            showToast(getString(R.string.login_phone_number_length_not_right));
        } else {
            check = true;
        }

        return check;
    }

    public String getPhone() {
        return mPhoneET.getText().toString();
    }

    private boolean checkPwd() {
        String pwd = getPwd();
        String code = getCode();

        boolean check = false;
        if (TextUtils.isEmpty(pwd)) {
            showToast(getString(R.string.register_password_require));
        } else if (pwd.length() < 6 || pwd.length() > 20) {
            showToast(getString(R.string.register_password_condition));
        } else if (!TextUtils.equals(pwd, code)) {
            showToast(getString(R.string.register_password_not_equals));
        } else {
            check = true;
        }

        return check;
    }

    public String getPwd() {
        return mPwdET.getText().toString();
    }

    private boolean checkCode() {
        String code = getCode();

        boolean check = false;
        if (TextUtils.isEmpty(code)) {
            showToast(getString(R.string.register_password_require));
        } else if (code.length() < 6 || code.length() > 20) {
            showToast(getString(R.string.register_password_condition));
        } else {
            check = true;
        }

        return check;
    }

    public String getCode() {
        return mCodeET.getText().toString();
    }

    @Override
    public void onBackPressed() {
        AppExitUtils.getInstance().onBackPressed(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_MOBILE_LOGIN && resultCode == RESULT_OK) {
            setResult(RESULT_OK);
            finish();
        }
    }
}
